package com.edooteach.tencent.web.controller.token;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.wechat.entity.token.JsTicket;
import com.demo2do.core.wechat.entity.token.Token;
import com.edooteach.tencent.accessor.WechatTokenAccessor;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("")
public class WechatTokenController {
    
    private static final Logger logger = LoggerFactory.getLogger(WechatTokenController.class);
    
    @Autowired
    private WechatTokenAccessor wechatTokenAccessor;
    
    /**
     * request wehcat access token
     * 
     * @return
     */
    @RequestMapping(value="/wechat/access-token", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult requestAccessToken() {
    
        HttpResult httpResult = new HttpResult();

        logger.trace("#requestAccessToken - Trying to request global access_token ... ");
    
        Token token = wechatTokenAccessor.requestAccessToken();
    
        httpResult.success().data("access_token", token.getAccessToken())
                            .data("expire", token.getExpire());
        
        return httpResult;
    }

    /**
     * request wehcat jsConfig
     * 
     * @return
     */
    @RequestMapping(value="/openapi/wechat/js-ticket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult requestJsTicket() {
        
        HttpResult httpResult = new HttpResult();
        
        logger.trace("#requestJsTicket - Trying to request wechat js_ticket ... ");
        
        JsTicket jsTicket = wechatTokenAccessor.requestJsTicket();
        
        if(jsTicket.isValid()) {
            
            return httpResult.success()
                             .data("appid", jsTicket.getAppid())
                             .data("ticket", jsTicket.getTicket())
                             .data("expire", jsTicket.getExpire());
            
        }
        
        return httpResult.fail("500").message("INVALID_JS_TICKET");
        
    }

}
